import { EmptyData, FormFieldType, SearchForm, SearchProps } from '@ycx/ui';
import { Col, Flex, Form, Pagination, PaginationProps, Row, Spin } from 'antd';
import EventCenterServices, { EventCenterListParams } from '@/api/services/eventCenterServices.ts';
import { keepPreviousData, useQuery } from '@tanstack/react-query';
import { useCatch } from '@/hooks';
import { useMemo, useState } from 'react';
import { Page } from '#/api.ts';
import TableCard from 'src/pages/eventCenter/components/TableCard';
import { useTheme } from '@/store/settingsStore.ts';
import { AlarmHandleStatus } from '#/enmu.ts';

const EventCenter = () => {
  const theme = useTheme();
  const [form] = Form.useForm<EventCenterListParams>();
  const catchFn = useCatch();
  const [apiParams, setApiParams] = useState<EventCenterListParams>();
  const [page, setPage] = useState<Page>({ page: 1, limit: 8, order: 'id DESC' });

  const { data: alarmTypeOptions } = useQuery({
    queryKey: ['alarmTypeList'],
    queryFn: () => catchFn(() => EventCenterServices.getAlarmTypeList()),
    select: ({ data }) => data.map((item) => ({ label: item, value: item })),
  });

  const { data: deviceOptions } = useQuery({
    queryKey: ['deviceList'],
    queryFn: () => catchFn(() => EventCenterServices.getDeviceList()),
    select: ({ data }) => data.map((item) => ({ label: item.carNo, value: item.carNo })),
  });

  const { data, refetch, isFetching } = useQuery({
    placeholderData: keepPreviousData,
    queryKey: ['eventCenterList', apiParams, page],
    queryFn: () => catchFn(() => EventCenterServices.getEventCenterList({ ...apiParams, ...page })),
    select: ({ data, total }) => ({
      data: data,
      total: total,
    }),
  });

  const searchProps: SearchProps<EventCenterListParams> = {
    form,
    fields: [
      {
        name: 'alarmDesc',
        label: '病害类型',
        type: FormFieldType.Select,
        fieldProps: {
          options: alarmTypeOptions,
        },
      },
      {
        name: 'handleStatus',
        label: '处理状态',
        type: FormFieldType.Select,
        fieldProps: {
          options: Object.entries(AlarmHandleStatus).map(([key, value]) => ({
            label: value,
            value: key,
          })),
        },
      },
      {
        name: 'alarmPosition',
        label: '报警位置',
        type: FormFieldType.Input,
      },
      {
        name: 'carNoList',
        label: '报警设备',
        type: FormFieldType.Select,
        //TODO: adjust gap of items
        fieldProps: {
          options: deviceOptions,
          mode: 'multiple',
          maxTagCount: 1,
        },
      },
    ],
    onSearch: async (formValues, isReset) => {
      if (JSON.stringify(formValues) === JSON.stringify(apiParams)) {
        await refetch();
      } else {
        setApiParams(formValues);
        setPage({ ...page, page: 1 });
      }
      if (isReset) setPage({ ...page, page: 1 });
    },
  };

  const paginationProps = useMemo<PaginationProps>(
    () => ({
      current: page.page,
      pageSize: page.limit,
      total: data?.total ?? 0,
      showSizeChanger: false,
      showTotal: (total) => `共 ${total} 条数据`,
      showQuickJumper: true,
      onChange: (page, pageSize) => setPage({ page, limit: pageSize, order: 'id DESC' }),
      pageSizeOptions: [],
    }),
    [page.page, page.limit, data],
  );

  return (
    <>
      <Flex vertical className="h-full">
        <SearchForm<EventCenterListParams> {...searchProps} />

        {data?.data && data.data.length ? (
          <>
            <div className="0 flex-1 overflow-x-hidden overflow-y-scroll px-2">
              <Spin spinning={isFetching}>
                <Row gutter={24}>
                  {data?.data.map((i) => (
                    <Col key={i.id} className="mb-6" xs={24} sm={24} md={24} lg={12} xl={8} xxl={6}>
                      <TableCard eventInfo={i} />
                    </Col>
                  ))}
                </Row>
              </Spin>
            </div>
            <Pagination {...paginationProps} className="pt-4"></Pagination>
          </>
        ) : (
          <Spin spinning={isFetching}>
            <EmptyData
              theme={theme}
              imageStyle={{
                width: '100%',
                height: '100%',
                minHeight: '150px',
              }}
            />
          </Spin>
        )}
      </Flex>
    </>
  );
};

export default EventCenter;
